package com.szyt.basicframe.service.impl;

import com.szyt.basicframe.common.ResponseResult;
import com.szyt.basicframe.pojo.bo.LoginUser;
import com.szyt.basicframe.pojo.request.UserLoginRequest;
import com.szyt.basicframe.service.ILoginService;
import com.szyt.basicframe.util.JwtUtil;
import com.szyt.basicframe.util.LoginUtil;
import com.szyt.basicframe.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {
    @Value("${login.expire}")
    private Long loginExpireTime;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public ResponseResult login(UserLoginRequest userDto) {
        // AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDto.getUserName(), userDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 认证没有通过
        if(Objects.isNull(authenticate)){
            // 粗略错误提示
            throw new RuntimeException("用户名或者密码错误");
        }
        // 认证通过，通过userid生成jwt,jwt存入响应体
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if(loginUser.getUser().getLocked()){
            throw new RuntimeException("用户已经停用，请与管理员联系");
        }
        String userId = loginUser.getUser().getId().toString();
        String jwt = jwtUtil.generateToken(userId);
        // 用户信息存入redis
        String redisKey = LoginUtil.getUserCacheKey(userId);
        redisUtil.set(redisKey, loginUser, loginExpireTime);
        // token响应为前端
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return ResponseResult.success("登陆成功", map);
    }
}
